<template>
  <el-dialog title="角色授权" :visible.sync="dialogShow" @close="closeDialog">
    <!-- //!渲染权限树 -->
    <!-- data是树的数据 prop是树展示的规则 label表示展示的文字 children表示子级的位置 -->
    <!-- check-strictly默认为false，表示父子关联,父勾选子也勾选 -->
    <!-- true表示不关联，父就是父，子就是子 -->
    <el-tree
      ref="tree"
      :check-strictly="true"
      node-key="id"
      show-checkbox
      :data="authList"
      :props="{ label: 'name' }"
      :default-checked-keys="checkAuth"
    />
    <el-row type="flex" justify="end">
      <el-button size="small" @click="dialogShow = false">取消</el-button>
      <el-button size="small" type="primary" @click="setAuthSubmit">
        确认
      </el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { tranListToTreeData } from '@/utils/index'
import { getPermissionListApi } from '@/api/permission'
import { getRoleInfoApi, setRoleAuthApi } from '@/api/setting'
export default {
  name: 'SetAuth',
  data() {
    return {
      dialogShow: false,
      authList: [], // 所有权限
      checkAuth: [], // 选中的权限ID数组
      roleId: null // 角色ID
    }
  },
  methods: {
    async getAllAuthList() {
      const res = await getPermissionListApi()
      this.authList = tranListToTreeData(res, '0')
    },
    // 获取当前角色信息
    async getCurRoleInfo(id) {
      this.roleId = id
      const res = await getRoleInfoApi(id)
      console.log(res)
      this.checkAuth = res.permIds
    },
    async setAuthSubmit() {
      // id角色ID  permIds打钩的树节点ID
      // this.$refs.tree.getCheckedKeys获取树打钩的ID
      const permIds = this.$refs.tree.getCheckedKeys()
      if (permIds.length === 0) return this.$message.warning('请勾选节点')

      await setRoleAuthApi({
        id: this.roleId,
        permIds
      })
      this.$message.success('关联权限成功')
      this.dialogShow = false
    },
    closeDialog() {
      this.roleId = null
      this.checkAuth = []
    }
  }
}
</script>

<style></style>
